import {
  login
} from '@/api/user'
import { setToken, getToken, setMemberId, getMemberId, setUserInfo, getUserInfo } from '@/libs/util'
export default {
  state: {
    userName: '',
    userId: '',
    avatorImgPath: '',
    memberId: getMemberId(),
    token: getToken(),
    access: getMemberId(),
    userAccount: '',
    userInfo: getUserInfo()
  },
  mutations: {
    setAvator (state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    setUserId (state, id) {
      state.userId = id
    },
    setUserName (state, name) {
      state.userName = name
    },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setMemberId (state, memberId) {
      state.memberId = memberId
      setMemberId(memberId)
    },
    setUserAssets (state, userAsset) {
      state.userAsset = userAsset
    },
    coinPrice (state, coinId) {
      state.coinPrice = coinId
    },
    setAccount (state, account) {
      state.userAccount = account
    },
    setUserInfo (state, info) {
      state.userInfo = info
    }
  },
  getters: {
    userAssets: state => state.userAsset,
    coinId: state => state.coinPrice,
    getAccess: state => state.access,
    userInfo: state => state.userInfo
  },
  actions: {
    // 登录
    handleLogin ({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          const data = res.data
          commit('setMemberId', data.storeId)
          commit('setToken', data.token)
          commit('setAvator', '')
          commit('setUserName', data.nickname)
          commit('setUserId', data.storeId)
          commit('setAccess', [data.storeId])
          commit('setUserInfo', data)
          setUserInfo(data)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setToken', '')
        commit('setAccess', [])
        commit('setUserInfo', {})
        setUserInfo({})
        resolve()
      })
    }
  }
}
